#!/usr/bin/perl

use strict;
use LWP::UserAgent;
use Crypt::SSLeay;
use JSON;
use HTTP::Cookies;
use HTTP::Status;
use Data::Dumper;

my $browser = LWP::UserAgent->new;
$browser->protocols_allowed( [ 'http', 'https'] );
my $cookieFile = "addama_lwp_cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
    file => $cookieFile,
  );
$cookie_jar->load($cookieFile);  
$browser->cookie_jar($cookie_jar);
$browser->timeout(100);
$browser->env_proxy;

if (@ARGV <= 0) {
  print "A url is required to run a GET command.  Example usage:\n  perl $0 http://yourhost/addama-rest/myRepo/someNode\n";
  exit(0);
}
my ($url) = @ARGV;

my $json = new JSON;
my $obj;
getUrl($url);

sub getUrl {
  my ($url) = @_;
  if($url) {
      my $response = $browser->get($url);

      if ($response->is_success) {
          my $response = $response->content;
          # eval in case response isn't legit json
          eval { $obj = $json->decode($response) };
          if (! $@) {
          	print $response;
          } else {
          	print Dumper $obj;
          } 
      }
      else {
          if($response->code()==401) {
            print "\nLogin is required, please run AddamaLogin.pl and try again.\n\n"
          } else {
            die $response->status_line;
          }
      }
  }
}

